/**
 * Copyright (c) 2009-2016, LarryKoo 老古 (gumutianqi@gmail.com)
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.plus.ext.handler;

import com.jfinal.handler.Handler;
import jodd.datetime.JDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * <a href = http://www.oschina.net/question/173052_62229 />
 * 计算一个网页的加载时间,只需要监测nextHandler的前后即可得到请求处理时间
 */
public class RenderingTimeHandler extends Handler {

    private final static Logger log = LoggerFactory.getLogger(RenderingTimeHandler.class);

    private String rendingTime = "rendingTime";

    public RenderingTimeHandler() {
    }

    public RenderingTimeHandler(String rendingTime) {
        this.rendingTime = rendingTime;
    }

    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        Long start = System.currentTimeMillis();
        next.handle(target, request, response, isHandled);
        Long end = System.currentTimeMillis();

        Long timer = end - start;
        if(timer > 0) {
            String endTimeFormat = new JDateTime(end).toString("YYYY-MM-DD hh:mm:ss");
            log.debug("<!-- Generated by gumutianqi@gmail.com ({}) {}ms -->", endTimeFormat, timer);
            Map<String, Object> map = new HashMap<>();
            map.put("end_time_millis", end);
            map.put("end_time_str", endTimeFormat);
            map.put("time", timer);
            request.setAttribute(rendingTime, map);
        }
    }

}
